const { Controller } = require('egg');
const crypto = require('crypto');
class UserController extends Controller {
    async reg() {
        this.ctx.validate({
            username: {
                type: "string",
                required: true,
                defValue: "",
                desc: "用户名称",
            },
            password: { type: "string", required: true, desc: "密码" },

        })
        let user = await this.app.model.User.findOne({
            where: {
                username: this.ctx.request.body.username

            }
        })
        if (user) {
            this.ctx.throw(400, "该用户已存在")
            return
        }
        let res = await this.app.model.User.create({
            username: this.ctx.request.body.username,
            password: this.ctx.request.body.password
        })
        this.ctx.apiSuccess(res, "ok", 200)
    }
    async login() {
        this.ctx.validate({
            username: {
                type: "string",
                required: true,
                defValue: "",
                desc: "用户名称",
            },
            password: { type: "string", required: true, desc: "密码" },

        })
        let user = await this.app.model.User.findOne({
            where: {
                username: this.ctx.request.body.username

            }
        })
        if (!user) {
            this.ctx.throw(400, "该用户不存在")
            return
        }
        console.log(user, "user")
        let checkpassword = await this.checkPassword(this.ctx.request.body.password, user.password)

        if (!checkpassword) {
            this.ctx.throw(400, "密码错误")
            return

        }
        let res1 = JSON.parse(JSON.stringify(user));
        let token = await this.getToken(res1);
        if (!await this.service.cache.set("user_" + user.id, token)) {
            this.ctx.throw(400, "登录失败");
            return
        }
        console.log(token, "token")
        res1.token = token
        this.ctx.apiSuccess(res1, "登录成功", 200)

    }
    async getsize(){
        let currentUser=this.ctx.authUser;
        console.log(currentUser,"virt")
        let data={}
        data.used_size=currentUser.used_size;
        data.total_size=currentUser.total_size;
        this.ctx.apiSuccess(data,"获取成功",200)
    }
    async getToken(value) {
        return this.app.jwt.sign(value, this.app.config.jwt.secret)
    }
    // 加密
    async createPassword(password) {
        const hmac = crypto.createHash("sha256", this.app.config.crypto.secret);
        hmac.update(password);
        return hmac.digest("hex");
    }

    // 验证密码
    async checkPassword(password, hash_password) {
        // 先对需要验证的密码进行加密
        password = await this.createPassword(password);
        return password === hash_password;
    }

}

module.exports = UserController;
